import React from 'react';
import ReactDOM from 'react-dom';
import Message from './Message';

import './Message.less';

class MessageBox extends React.Component {
    displayName = 'MessageBox';

    _id = 1;

    state = {
        items: []
    }

    renderMessages () {
        return this.state.items.map(item => {
            return <Message key={item.key} data={item} onClose={this.onClose}/>;
        });
    }

    onClose = (key) => {
        const items = this.state.items.filter(item => {
            return item.key !== key;
        });
        this.setState({items}, () => {
            if (this.props.onClose) {
                this.props.onClose(key);
            }
        });
    }

    info (config) {
        if (typeof config === 'string') {
            config = {
                content: config
            };
        }
        config.type = 'info';
        this.open(config);
    }

    success (config) {
        if (typeof config === 'string') {
            config = {
                content: config
            };
        }
        config.type = 'success';
        this.open(config);
    }

    warning (config) {
        if (typeof config === 'string') {
            config = {
                content: config
            };
        }
        config.type = 'warning';
        this.open(config);
    }

    error (config) {
        if (typeof config === 'string') {
            config = {
                content: config
            };
        }
        config.type = 'error';
        this.open(config);
    }

    loading (config) {
        if (typeof config === 'string') {
            config = {
                content: config
            };
        }
        config.loading = true;
        this.open(config);
        return this.onClose.bind(this, config.key);
    }

    open (config) {
        const items = this.state.items;
        if (!config.key) {
            this._id ++;
            config.key = `cm-msg-${this._id}`;
        }
        items.push(config);
        this.setState({items});
    }

    render () {
        return <div className='cm-messages'>
            {this.renderMessages()}
        </div>;
    }
}

let message = null;
if (window.message) {
    message = window.message;
} else {
    const ele = document.createElement('div');
    ele.className = 'cm-messages-wrap';
    document.body.appendChild(ele);
    message = ReactDOM.render(<MessageBox />, ele);
}

export default message;
